package com.springboot.springbootweb.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.springboot.springbootweb.model.JcUser;
import com.springboot.springbootweb.service.JcUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author gwj
 * @since 2021-09-11
 */
@RestController
@RequestMapping("/jc-user")
public class JcUserController {
    @Autowired
    private JcUserService jcUserService;

    /**
     * 返回整个结果
     *
     * @return
     */
    @GetMapping("/users")
    @ResponseStatus(HttpStatus.OK)
    public List<JcUser> getAllUser() {
        return jcUserService.list();
    }

    /**
     * 返回整个结果
     *
     * @return
     */
    @GetMapping("/userspage1")
    @ResponseStatus(HttpStatus.OK)
    public Page userspage1(HttpServletRequest request) {
        int offset = Integer.parseInt(request.getParameter("offset"));
        int limit = Integer.parseInt(request.getParameter("limit"));
        int id = Integer.parseInt(request.getParameter("id"));
        Page page = new Page<>(offset / limit + 1, limit);
        Page projectWinInfoList = (Page) jcUserService.getAll(page, id);
        return projectWinInfoList;
    }

    /**
     * 返回整个结果
     *
     * @return
     */
    @GetMapping("/userspage")
    @ResponseStatus(HttpStatus.OK)
    public List<JcUser> getAllUserPage() {
        return jcUserService.getAllUserPage();
    }


    /**
     * 返回指定的结果
     *
     * @param id
     * @return
     */
    @GetMapping("/users/{id}")
    @ResponseStatus(HttpStatus.OK)
    public Object getUser(@PathVariable("id") String id) {
        return jcUserService.getById(id);
    }

    /**
     * 新增一个用户
     *
     * @param user
     * @return 无注解（form提交）
     * Body参数application/jason
     * 地址传值
     * @PathVariable ? 传值
     * @RequestParam
     */
    @PostMapping("/users")
    @ResponseStatus(HttpStatus.CREATED)
    public Object addUser(JcUser user) {
        return jcUserService.save(user);
    }


    /**
     * 修改用户（使用的是id来改但是update并没有id的主键修改）
     *
     * @param id
     * @param user
     * @return
     */
    @PutMapping("/users/{id}")
    @ResponseStatus(HttpStatus.CREATED)
    public Object editUser(@PathVariable("id") String id,
                           JcUser user) {
        QueryWrapper<JcUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        return jcUserService.update(user, queryWrapper);
    }

    /**
     * 删除一个用户
     *
     * @param id
     * @return
     */
    @DeleteMapping("/users/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public Object deleteUser(@PathVariable("id") String id) {
        return jcUserService.removeById(id);
    }
}
